/**
 * @description 封装取消 axios 请求工具类，防止段时间频繁发送相同 http 请求
 */
import axios from "axios";

const pending = new Map();

/**
 * 添加请求
 * @param config
 */
export const addPending = (config)=> {
    const url = [
        config.method,
        config.url,
        JSON.stringify(config.params),
        JSON.stringify(config.data)
    ].join('&');
    config.cancelToken = config.cancelToken ||  new axios.CancelToken(cancel => {
        // 如果 pending 中不存在当前请求，则添加进去
        if (!pending.has(url)) {
            pending.set(url, cancel)
        }
    })
}

/**
 * 移除请求
 * @param config
 */
export const removePending = (config)=> {
    const url = [
        config.method,
        config.url,
        JSON.stringify(config.params),
        JSON.stringify(config.data)
    ].join('&');
    if(pending.has(url)) {
        const cancel = pending.get(url)
        cancel(url)
        pending.delete(url)
    }
}

/**
 * 清空 pending 中的请求
 */
export const clearPending = () => {
    for (const [url, cancel] of pending) {
        cancel(url)
    }
    pending.clear()
}